#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

using namespace std;

void error(const char *msg) {
    perror(msg);
    exit(1);
}

int main() {
    int client_socket;
    struct sockaddr_in serv_addr;
    char buffer[256];

    // 创建socket
    client_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (client_socket < 0)
        error("ERROR opening socket");

    // 初始化服务器地址结构
    memset((char *) &serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(6666); // 服务器端口
    inet_pton(AF_INET, "192.168.227.128", &serv_addr.sin_addr); // 服务器IP地址

    // 连接到服务器
    if (connect(client_socket, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    cout << "Connected to server. Enter message to send: ";

    while(1){
    string message;
    getline(cin, message);

    // 发送消息到服务器
    int n = send(client_socket, message.c_str(), message.size(), 0);
    if (n < 0)
        error("ERROR writing to socket");

    // 接收服务器响应
    memset(buffer, 0, sizeof(buffer));
    n = recv(client_socket, buffer, sizeof(buffer) - 1, 0);
    if (n < 0)
        error("ERROR reading from socket");

    cout << "Server response: " << buffer << endl;
    }
    // 关闭socket
    close(client_socket);


    return 0;
}
